<?php
/**
 * @Author:      zwh
 * @DateTime:    2017-3-15 14:14:17
 * @Description: 用于 mkt 活动包管理
 */
class MktProductActivityController extends BaseController {
    
    
    /**
     * @Author:      zwh
     * @DateTime:    2017-4-10 15:24:18
     * @Description: 活动包详情
     */
    public function show(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'product_activity_id'=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $mkt_user=$this->verificationMKTUserToken(Input::get("token"),$response);
            if(is_null($mkt_user)){
                break;
            }
    
            $pa=ProductActivity::find(Input::get('product_activity_id'));
            $pa->price=bcdiv($pa->price,100,2);
            $pap=ProductActivityPackage::where('product_activity_id',Input::get('product_activity_id'))->select('package_id')->get();
            $pa->packages=$pap;
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("product_activity"=>$pa));
        }while(false);
        Log::info("info", array("system" => "mkt" ,"event" => "show", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zy
     * @DateTime:    2017-8-30 15:24:18
     * @Description: 活动包内容-》耗材详情
     */
    public function item_show(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'product_activity_id'=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $mkt_user=$this->verificationMKTUserToken(Input::get("token"),$response);
            if(is_null($mkt_user)){
                break;
            }

            $pap=ProductActivityPackage::leftJoin("product_package","product_activity_package.package_id","=","product_package.id")
                    ->where('product_activity_id',Input::get('product_activity_id'))
                    ->select('package_id','product_activity_package.id','product_package.name')->get();

            if (!empty($pap)){
                foreach ($pap as $value){
                    $product_pack_item = ProductPackItem::leftjoin("supply_classification","supply_classification.id","=","product_pack_item.item_id" )
                            ->where("pack_id",$value->package_id)
                            ->where("type",3)
                            ->where("product_pack_item.status",1)
                            ->select("supply_classification.name","product_pack_item.item_id")
                            ->get();

                    foreach ($product_pack_item as $v) {
                        $papi = ProductActivityPackageItem::where("subject",$v->item_id)
                                ->where("product_activity_package_item.product_activity_package_id",$value->id)
                                ->select("id","supply_item_id","number")
                                ->first();
                        
                        $v->papi = $papi;
                        if (!empty($papi->supply_item_id)) {
                            $v->item = SupplyItem::getCacheItemInfo($papi->supply_item_id);
                        }
                    }
                    $value->product_pack_item = $product_pack_item;
                }
                //$value->id => product_activity_package_id    
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("pap"=>$pap));
        }while(false);
        Log::info("info", array("system" => "mkt" ,"event" => "show", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zy
     * @DateTime:    2017-8-31
     * @Description: 根据brand_id 和 retrieval_code搜索
     */
    public function item_serch(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'subject'=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $mkt_user=$this->verificationMKTUserToken(Input::get("token"),$response);
            if(is_null($mkt_user)){
                break;
            }
            $subject = Input::get("subject");
            if(is_null($subject)){
                $response = Lang::get("mkt_error.subject_notexiet_40000");
                break;
            }
            
            $brand_id = Input::get("brand_id");
            $retrieval_code = Input::get("retrieval_code");
            if (is_null($brand_id) && is_null($retrieval_code)) {//两个值不能同时为空
                $response = Lang::get("mkt_error.brandid_retrieval_codenotexiet_40000");
                break;
            }
            
            $si_arr=SupplyItem::where("status",1)->where("supply_classification_id",$subject)->select("supply_item.id");
            if(!empty($brand_id)) $si_arr = $si_arr->where("supply_item.brand_id",$brand_id);
            if(!empty($retrieval_code)) $si_arr = $si_arr->where("supply_item.retrieval_code","like",'%'.$retrieval_code.'%');
            $si_arr = $si_arr->take(100)->get();

            $finally=array();
            foreach ($si_arr as $_s) {
                $item_info=SupplyItem::getCacheItemInfo($_s->id);
                $scf=SupplyClassification::getClassification($item_info->st_classifi_id);                
                $item_info->two_id=$scf->two_id;
                $item_info->two=$scf->two;
                $item_info->one_id=$scf->one_id;
                $item_info->one=$scf->one;
                $item_info->car_model_comments=$item_info->car_model_comments;
                $finally[]=$item_info;
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("si_arr"=>$finally));
        }while(false);
        //supply_item.id => supply_item_id  ,    supply_item.subject=>subject   number=>number
        Log::info("info", array("system" => "mkt" ,"event" => "show", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      zy
     * @DateTime:    2017-9-1
     * @Description: 取消活动包内容 包含的耗材
     */
    public function del_papi(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'product_activity_package_item_id'=> 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $mkt_user=$this->verificationMKTUserToken(Input::get("token"),$response);
            if(is_null($mkt_user)){
                break;
            }
            $result = DB::table('product_activity_package_item')->where('id', Input::get("product_activity_package_item_id"))->delete();

            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        }while(false);
        Log::info("info", array("system" => "mkt" ,"event" => "show", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    public function supply_item_lists(){
    
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'subject'=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $mkt_user=$this->verificationMKTUserToken(Input::get("token"),$response);
            if(is_null($mkt_user)){
                break;
            }
            $si_sb = DB::table('supply_item')
                ->where('supply_classification_id',Input::get("subject"))
                ->distinct('brand_name')->select('brand_id','brand_name')
                ->get();
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $si_sb);
        }while(false);
        Log::info("info", array("system" => "mkt" ,"event" => "show", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zy
     * @DateTime:    2017-9-1
     * @Description: 创建活动包内容下的 耗材
     */
    public function create_pap_items(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'product_activity_package_id'=> 'required',
                'number'=>'required',
                'supply_item_id'=>'required',
                'subject'=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $mkt_user=$this->verificationMKTUserToken(Input::get("token"),$response);
            if(is_null($mkt_user)){
                break;
            }

            $product_activity_package_item_id = Input::get('product_activity_package_item_id');
            if (!empty($product_activity_package_item_id)) {
                $papi = ProductActivityPackageItem::find($product_activity_package_item_id);
            }else {
                $papi = new ProductActivityPackageItem();
            }

            $papi->product_activity_package_id = Input::get('product_activity_package_id');
            $papi->number = Input::get('number');
            $papi->supply_item_id = Input::get('supply_item_id');
            $papi->subject = Input::get('subject');
            $papi->save();
            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("id"=>$papi->id));
        }while(false);
        Log::info("info", array("system" => "mkt" ,"event" => "show", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    
    /**
     * @Author:      zwh
     * @DateTime:    2017-3-15 14:14:40
     * @Description: 创建活动包
     * http://www.activity.com/v1/mkt/product_activity/create?token=c6b0ab3cfb66b3c6d9fd57a28488f2f8&name=%E6%B5%8B%E8%AF%95&type=1&status=1&is_edit=1&pack_ids=[%202,%206%20]&begin_time=2018-06-04%2018:03:10&end_time=2019-03-02%2012:20:34
     */
    public function create(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'name' => 'required|max:255',
                'type'=>'required',
                // 'begin_time'=>'required',
                // 'end_time'=>'required',
                // 'desc'=>'required',
                'pack_ids'=>'required',
                'status'=>'required',
                'is_edit'=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $mkt_user=$this->verificationMKTUserToken(Input::get("token"),$response);
            if(is_null($mkt_user)){
                break;
            }

            $pa=new ProductActivity();
            $pa->name = Input::get('name');
            $pa->type = Input::get('type');
            if(Input::get('type')==1){
                $pa->price = Input::get('price')*100;
            }else{
                $pa->discount = Input::get('discount');
            }
            $pa->status = Input::get('status');
            if(Input::get('begin_time')){
                $pa->begin_time = Input::get('begin_time');
                $pa->end_time = Input::get('end_time'); 
            }            
            $pa->desc = Input::get('desc');
            $pa->created_by = $mkt_user->id;
            $pa->updated_by = 0;
            $pa->is_edit = Input::get('is_edit',1);
            $pa->is_member=Input::get("is_member",0);
            $pa->save();

            $pack_ids=json_decode(Input::get('pack_ids'),1);
            foreach($pack_ids as $pack_id){
                $pap = new ProductActivityPackage();
                $pap->product_activity_id = $pa->id;
                $pap->package_id = $pack_id;
                $pap->created_by = $mkt_user->id;
                $pap->save();
            }

            //创建活动包站内信
            $notice = ScNotice::InsertProductNotice($pa->id,Input::get('name'),$pa->type,$pa->price,$pa->discount,Input::get('status'),$pa->begin_time,$pa->end_time,Input::get('desc'),Input::get("is_member",0),$mkt_user->id,$pa->is_edit,ScNotice::$product_type);

            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("product_activity_id"=>$pa->id));
        }while(false);
        Log::info("info", array("system" => "mkt" ,"event" => "create", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2017-3-15 14:14:40
     * @Description: 编辑活动包
     * http://www.activity.com/v1/mkt/product_activity/update?token=c6b0ab3cfb66b3c6d9fd57a28488f2f8&name=%E6%B5%8B%E8%AF%95&type=1&status=1&is_edit=1&pack_ids=[%202,%206%20]&begin_time=2018-06-04%2018:03:10&end_time=2019-03-02%2012:20:34&product_activity_id=90
     */
    public function update(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'product_activity_id'=>'required',
                'name' => 'required|max:255',
                'type'=>'required',
                // 'begin_time'=>'required',
                // 'end_time'=>'required',
                // 'desc'=>'required',
                'pack_ids'=>'required',
                'status'=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $mkt_user=$this->verificationMKTUserToken(Input::get("token"),$response);
            if(is_null($mkt_user)){
                break;
            }
    
            $pa=ProductActivity::find(Input::get('product_activity_id'));
            $pa->name = Input::get('name');
            $pa->type = Input::get('type');
            if(Input::get('type')==1){
                $pa->price = Input::get('price')*100;
                $pa->discount = 1;
            }else{
                $pa->price = 0;
                $pa->discount = Input::get('discount');
            }
            $pa->status = Input::get('status');
            $pa->begin_time = Input::get('begin_time');
            $pa->end_time = Input::get('end_time');
            $pa->desc = Input::get('desc');
            $pa->updated_by = $mkt_user->id;
            $pa->save();
    
            ProductActivityPackage::where('product_activity_id',Input::get('product_activity_id'))->delete();
            $pack_ids=json_decode(Input::get('pack_ids'),1);
            foreach($pack_ids as $pack_id){
                $pap = new ProductActivityPackage();
                $pap->product_activity_id = $pa->id;
                $pap->package_id = $pack_id;
                $pap->created_by = $mkt_user->id;
                $pap->save();
            }

            //修改活动包站内信
            $notice = ScNotice::UpdateProductNotice(Input::get('product_activity_id'),Input::get('name'),$pa->type,$pa->price,$pa->discount,Input::get('status'),$pa->begin_time,$pa->end_time,Input::get('desc'),Input::get("is_member",0),$mkt_user->id,$pa->is_edit,ScNotice::$product_type);

            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("product_activity_id"=>Input::get('product_activity_id')));
        }while(false);
        Log::info("info", array("system" => "mkt" ,"event" => "update", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      zwh
     * @DateTime:    2017-3-15 15:47:24
     * @Description: 活动包列表
     */
    public function lists(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "page"=>'integer',
                "page_size"=>'integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $mkt_user=$this->verificationMKTUserToken(Input::get("token"),$response);
            if(is_null($mkt_user)){
                break;
            }
            $page_size=Input::get("page_size",20);
            $page=Input::get("page",1);
            $time=Input::get("time");
            
            $pas=ProductActivity::orderBy('created_at','desc');
            
            if(Input::get("name")){
                $pas->where("name",'like','%'.Input::get("name").'%');
            }
            
            if(Input::get('begin_time')!=""){
                $pas->where("begin_time",'>=',Input::get('begin_time')." 00:00:00");
            }
            if(Input::get('end_time')!=""){
                $pas->where("end_time",'<=',Input::get('end_time')." 23:59:59");
            }
            if(Input::get("status")!=""){
                $pas->where("status",Input::get("status"));
            }
            
            $count=$pas->count();
            $pas=$pas->skip($page_size*($page-1))->take($page_size)->get();
            foreach($pas as $_pas){
                $create_by=MktUser::find($_pas->created_by);
                $update_by=MktUser::find($_pas->updated_by);
                $_pas->created_name=isset($create_by->real_name) ? $create_by->real_name :"";
                $_pas->updated_name=isset($update_by->real_name) ? $update_by->real_name :"";
            }
            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>$count,"activites"=>$pas));
        }while(false);
        Log::info("info", array("system" => "mkt" ,"event" => "lists", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      zwh
     * @DateTime:    2017-3-20 15:29:24
     * @Description: 城市列表
     */
    public  function city_list(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'product_activity_id' => 'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $mkt_user=$this->verificationMKTUserToken(Input::get("token"),$response);
            if(is_null($mkt_user)){
                break;
            }
            
            //根据适配的城市表获取适配的城市
            $pac=ProductActivityCity::where("product_activity_id",Input::get('product_activity_id'))->where("status",1)->get();
            $citys=array();
            foreach($pac as $_pac){                
                $citys[]=$_pac->city_id;
            }
            
//            //通过门店获取适配的城市，
//            $pas=ProductActivityShop::where("product_activity_id",Input::get('product_activity_id'))->get();
//            $citys=array();
//            foreach($pas as $_pas){
//                $ms=MaintenanceShops::find($_pas->shop_id);
//                if(!in_array($ms->city_id,$citys)){
//                    $citys[]=$ms->city_id;
//                }
//            }
            $all_cit=DB::select("select rct.id,rct.name,rpt.id rid ,rpt.`name` p_name from resource_city_type rct LEFT JOIN resource_city rc on rc.id=rct.id
                    LEFT JOIN resource_province_type rpt on rpt.id=rc.province_id where rct.`status`=1");
            foreach ($all_cit as $_r) {
                if(isset($resource_arr[$_r->rid])){
                    $temparr=$resource_arr[$_r->rid];
                    $temparr["item"][]=$_r;
                    $resource_arr[$_r->rid]=$temparr;
                }else{
                    $resource_arr[$_r->rid]=array(
                        'r_id'=>$_r->rid,
                        'name'=>$_r->p_name,
                        'item'=>array($_r),
                    );
                }
            }
            $resource_arr=array_values($resource_arr);
            foreach($resource_arr as $ra){
                foreach($ra['item'] as $item){
                    if(in_array($item->id,$citys)){
                        $item->status=1;
                    }else{
                        $item->status=0;
                    }
                }
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array('city_list'=>$resource_arr));
        }while(false);
        Log::info("info", array("system" => "mkt" ,"event" => "city_list", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2017-4-11 14:59:57
     * @Description: 配置省份下城市
     */
    public function save_citys(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'product_activity_id' => 'required',
                'city_ids'=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $mkt_user=$this->verificationMKTUserToken(Input::get("token"),$response);
            if(is_null($mkt_user)){
                break;
            }
            $city_ids=json_decode(Input::get('city_ids'));
            ProductActivityCity::where("product_activity_id",Input::get('product_activity_id'))->where("status",1)->update(array('status'=>0));
            foreach ($city_ids as $_c) {
                $pac=new ProductActivityCity();
                $pac->product_activity_id = Input::get('product_activity_id');
                $pac->city_id = $_c;
                $pac->created_by = $mkt_user->id;
                $pac->status =1;
                $pac->save();
            }
/**
 * 修改城市适配的时候，不修改当前城市下所有门店  20170925 赵洋
 */            
//            $ms=MaintenanceShops::whereIn('city_id',$city_ids)->where('status',1)->get();
            ProductActivityShop::where('product_activity_id',Input::get('product_activity_id'))->delete();
            ScNoticeShop::where('activity_base_id',Input::get('product_activity_id'))->delete();
//            foreach($ms as $_ms){
//                $pas=new ProductActivityShop();
//                $pas->product_activity_id = Input::get('product_activity_id');
//                $pas->shop_id = $_ms->id;
//                $pas->created_by = $mkt_user->id;
//                $pas->save();
//            }
    
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("product_activity_id"=>Input::get('product_activity_id')));
        }while(false);
        Log::info("info", array("system" => "mkt" ,"event" => "save_shops", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2017-3-20 15:33:52
     * @Description: 某城市下门店列表
     */
    public  function shop_list(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'product_activity_id' => 'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $mkt_user=$this->verificationMKTUserToken(Input::get("token"),$response);
            if(is_null($mkt_user)){
                break;
            }
            
//            $pas=ProductActivityShop::leftJoin('maintenance_shops','maintenance_shops.id','=','product_activity_shop.shop_id')
//                ->where("product_activity_id",Input::get('product_activity_id'))
//                ->distinct('city_id')
//                ->select('city_id')
//                ->get();
            
            $pas=ProductActivityCity::where("product_activity_id",Input::get('product_activity_id'))->where("status",1)->get();  
            $shop_ids=ProductActivityShop::where('product_activity_id',Input::get('product_activity_id'))->select('shop_id')->get()->toArray();
            $shop_ids=array_column($shop_ids,'shop_id');
            $citys=array();
            foreach($pas as $_pas){
                // $ms=MaintenanceShops::where('city_id',$_pas->city_id)->where('status',1)->select('id','name')->get();
                $ms=MaintenanceShops::leftJoin("resource_region","resource_region.id","=","maintenance_shops.region_id")->where('maintenance_shops.city_id',$_pas->city_id)->where('maintenance_shops.status',1)->select('maintenance_shops.id','maintenance_shops.name',"resource_region.region_name")->get();
                $citys[]=array('id'=>$_pas->city_id,'item'=>$ms);
            }
            foreach($citys as $key=>$city){
                $cc=CommonCity::find($city['id']);
                $citys[$key]['name']=$cc->name;
                foreach($city['item'] as $item){
                    if(in_array($item->id,$shop_ids)){
                        $item->status=1;
                    }else{
                        $item->status=0;
                    }
                }
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("shop_info"=>$citys));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "shop_list", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2017-3-20 15:42:59
     * @Description: 配置活动门店
     */
    public function save_shops(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'product_activity_id' => 'required',
                'shop_ids'=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $mkt_user=$this->verificationMKTUserToken(Input::get("token"),$response);
            if(is_null($mkt_user)){
                break;            
            }
            $shop_ids=json_decode(Input::get('shop_ids'),1);
            ProductActivityShop::where('product_activity_id',Input::get('product_activity_id'))->delete();
            foreach($shop_ids as $shop_id){
                $pas=new ProductActivityShop();
                $pas->product_activity_id = Input::get('product_activity_id');
                $pas->shop_id = $shop_id;
                $pas->created_by = $mkt_user->id;
                $pas->save();
            }

            //站内信活动包门店适配
            $shop = ScNoticeShop::ProductShop(Input::get('product_activity_id'));
            $notice_id = ScNotice::Notice(Input::get('product_activity_id'), 2);
            if(is_null($notice_id)){
                $response = Lang::get("mkt_error.mkt_notice_activity_exit_error_400001");
                break;
            }
            $notice = ScNotice::SaveShop(Input::get('product_activity_id'),2,$shop_ids,$mkt_user->id,$notice_id['id']);

            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("product_activity_id"=>Input::get('product_activity_id')));
        }while(false);
        Log::info("info", array("system" => "mkt" ,"event" => "save_shops", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    
    /**
     * @Author:      zwh
     * @DateTime:    2017-4-12 10:57:54
     * @Description: 统计
     */
    public function statistics(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'product_activity_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $mkt_user=$this->verificationMKTUserToken(Input::get("token"),$response);
            if(is_null($mkt_user)){
                break;
            }
            //门店模糊搜索
            if(Input::get('shop_name')!=""){
                $ms_ids=MaintenanceShops::where('name','like','%'.Input::get('shop_name').'%')->select('id')->get()->toArray();
                $ms_ids=array_column($ms_ids,'id');
            }
            
            //城市搜索
            if(Input::get('city_id')!=""){
                $ms_ids=MaintenanceShops::where('name','like','%'.Input::get('shop_name').'%')->select('id')->get()->toArray();
                $ms_ids=array_column($ms_ids,'id');
            }
            
            
            $shop_ids=ProductActivityShop::leftJoin('maintenance_shops','maintenance_shops.id','=','product_activity_shop.shop_id')
            ->where('product_activity_id',Input::get('product_activity_id'))
            ->select('shop_id');
            if(Input::get('shop_name')!=""){
                $shop_ids=$shop_ids->whereIn('shop_id',$ms_ids);
            }
            if(Input::get('city_id')!=""){
                $shop_ids=$shop_ids->where('maintenance_shops.city_id',Input::get('city_id'));
            }
            $shop_ids=$shop_ids->get()->toArray();
            $shop_ids=array_column($shop_ids,'shop_id');
            $shop_ids=array_unique($shop_ids);
            sort($shop_ids);
            $beginToday=mktime(0,0,0,date('m'),date('d'),date('Y'));
            $endToday=mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
            $start=date('Y-m-d H:i:s',$beginToday);
            $end=date('Y-m-d H:i:s',$endToday);
            
            
            $statistics=array();
//             //门店总数
//             $shop_num=OrderProduct::leftJoin('orders','orders.order_id','=','order_product.order_id')
//                 ->leftJoin('maintenance_shops','maintenance_shops.id','=','orders.shop_id')
//                 ->whereIn('orders.status',Orders::$complete)
//                 ->where('order_product.status',1)
//                 ->where('order_product.product_type','activity')
//                 ->where('order_product.product_id',Input::get('product_activity_id'))
//                 ->select('shop_id')
//                 ->distinct('shop_id');
//             if(Input::get('shop_name')!=""){
//                 $shop_num=$shop_num->whereIn('shop_id',$ms_ids);
//             }
//             if(Input::get('city_id')!=""){
//                 $shop_num=$shop_num->where('maintenance_shops.city_id',Input::get('city_id'));
//             }
//             $shop_num=$shop_num->count();
            $statistics['sum_shop_num']=count($shop_ids);
//             //城市总数
//             $city_num=OrderProduct::leftJoin('orders','orders.order_id','=','order_product.order_id')
//                 ->leftJoin('maintenance_shops','maintenance_shops.id','=','orders.shop_id')
//                 ->whereIn('orders.status',Orders::$complete)
//                 ->where('order_product.status',1)
//                 ->where('order_product.product_id',Input::get('product_activity_id'))
//                 ->where('order_product.product_type','activity')
//                 ->select('city_id')
//                 ->distinct('city_id');
//             if(Input::get('shop_name')!=""){
//                 $city_num=$city_num->whereIn('shop_id',$ms_ids);
//             }
//             if(Input::get('city_id')!=""){
//                 $city_num=$city_num->where('maintenance_shops.city_id',Input::get('city_id'));
//             }
//             $city_num=$city_num->count();
            $city_ids=MaintenanceShops::whereIn('id',$shop_ids)->select('city_id')->distinct('city_id')->get();
            $statistics['sum_city_num']=count($city_ids);
            //总销量
            $sales_num=OrderProduct::leftJoin('orders','orders.order_id','=','order_product.order_id')
                ->whereIn('orders.status',Orders::$complete)
                ->where('product_type','activity')
                ->where('order_product.product_id',Input::get('product_activity_id'))
                ->where('order_product.status',1);
            if(Input::get('shop_name')!=""){
                $sales_num=$sales_num->whereIn('shop_id',$ms_ids);
            }
            if(Input::get('city_id')!=""){
                $sales_num=$sales_num->where('orders.city',Input::get('city_id'));
            }
            $sales_num=$sales_num->count();
            $statistics['sum_sales_num']=$sales_num;
            //总收益(一口价加上未打折前活动包价格)
            $sales_amount=OrderProduct::leftJoin('orders','orders.order_id','=','order_product.order_id')
                ->whereIn('orders.status',Orders::$complete)
                ->where('product_type','activity')
                ->where('order_product.product_id',Input::get('product_activity_id'))
                ->where('order_product.status',1);
            if(Input::get('shop_name')!=""){
                $sales_amount=$sales_amount->whereIn('shop_id',$ms_ids);
            }
            if(Input::get('city_id')!=""){
                $sales_amount=$sales_amount->where('orders.city',Input::get('city_id'));
            }
            $sales_amount=$sales_amount->sum('order_product.amount');
            //活动包打折优惠价格
            $dis_amount=OrderProduct::leftJoin('orders','orders.order_id','=','order_product.order_id')
            ->whereIn('orders.status',Orders::$complete)
            ->where('product_type','activity')
            ->where('order_product.product_id',Input::get('product_activity_id'))
            ->where('order_product.status',1);
            if(Input::get('shop_name')!=""){
                $dis_amount=$dis_amount->whereIn('shop_id',$ms_ids);
            }
            if(Input::get('city_id')!=""){
                $dis_amount=$dis_amount->where('orders.city',Input::get('city_id'));
            }
            $dis_amount=$dis_amount->sum('order_product.discount');
            $statistics['sum_sales_amount']=($sales_amount-$dis_amount)/100;//上面两者相减得出收益
            

            $statistics_detail=array();
            //各个门店销量及收益情况
            foreach($shop_ids as $shop_id){
                $shop=array();
                $shop['shop_id']=$shop_id;
                $ms=MaintenanceShops::find($shop_id);
                $shop['shop_name']=$ms->name;
                $cc=CommonCity::find($ms->city_id);
                $shop['city_id']=$ms->city_id;
                $shop['city_name']=$cc->name;
                //当前门店总收益
                $sale_amount=OrderProduct::leftJoin('orders','orders.order_id','=','order_product.order_id')
                    ->whereIn('orders.status',Orders::$complete)
                    ->where('product_type','activity')
                    ->where('orders.shop_id',$shop_id)
                    ->where('order_product.status',1)
                    ->where('order_product.product_id',Input::get('product_activity_id'))
                    ->sum('order_product.amount');
                $dis_amount=OrderProduct::leftJoin('orders','orders.order_id','=','order_product.order_id')
                    ->whereIn('orders.status',Orders::$complete)
                    ->where('product_type','activity')
                    ->where('orders.shop_id',$shop_id)
                    ->where('order_product.status',1)
                    ->where('order_product.product_id',Input::get('product_activity_id'))
                    ->sum('order_product.discount');
                $shop['sale_amount']=($sale_amount-$dis_amount)/100;
                //当前门店总销量
                $sale_num=OrderProduct::leftJoin('orders','orders.order_id','=','order_product.order_id')
                    ->whereIn('orders.status',Orders::$complete)
                    ->where('product_type','activity')
                    ->where('orders.shop_id',$shop_id)
                    ->where('order_product.product_id',Input::get('product_activity_id'))
                    ->where('order_product.status',1)
                    ->count();
                $shop['sale_num']=$sale_num;
                //当前门店今日总收益
                $sale_amount_today=OrderProduct::leftJoin('orders','orders.order_id','=','order_product.order_id')
                    ->whereIn('orders.status',Orders::$complete)
                    ->where('product_type','activity')
                    ->where('orders.shop_id',$shop_id)
                    ->where('order_product.status',1)
                    ->where('pay_time','>',$start)
                    ->where('pay_time','<',$end)
                    ->where('order_product.product_id',Input::get('product_activity_id'))
                    ->sum('order_product.amount');
                $dis_amount_today=OrderProduct::leftJoin('orders','orders.order_id','=','order_product.order_id')
                    ->whereIn('orders.status',Orders::$complete)
                    ->where('product_type','activity')
                    ->where('orders.shop_id',$shop_id)
                    ->where('order_product.status',1)
                    ->where('pay_time','>',$start)
                    ->where('pay_time','<',$end)
                    ->where('order_product.product_id',Input::get('product_activity_id'))
                    ->sum('order_product.discount');
                $shop['sale_amount_today']=($sale_amount_today-$dis_amount_today)/100;
               //当前门店今日总销量
                $sale_num_today=OrderProduct::leftJoin('orders','orders.order_id','=','order_product.order_id')
                    ->whereIn('orders.status',Orders::$complete)
                    ->where('product_type','activity')
                    ->where('orders.shop_id',$shop_id)
                    ->where('order_product.status',1)
                    ->where('pay_time','>',$start)
                    ->where('pay_time','<',$end)
                    ->where('order_product.product_id',Input::get('product_activity_id'))
                    ->count();
                $shop['sale_num_today']=$sale_num_today;
                $statistics_detail[]=$shop;
            }   

            //城市搜索
            if(Input::get('sort')!="" && sizeof($statistics_detail)>0){
                if(Input::get('sort')==1){//总销量降序
                    foreach($statistics_detail as $key=>$sd){
                        $arr[$key]=$sd['sale_num'];
                    }
                    array_multisort($arr, SORT_DESC,$statistics_detail);
                }
                if(Input::get('sort')==2){//总销量升序
                    foreach($statistics_detail as $key=>$sd){
                        $arr[$key]=$sd['sale_num'];
                    }
                    array_multisort($arr, SORT_ASC,$statistics_detail);
                }
                if(Input::get('sort')==3){//今日销量降序
                    foreach($statistics_detail as $key=>$sd){
                        $arr[$key]=$sd['sale_num_today'];
                    }
                    array_multisort($arr, SORT_DESC,$statistics_detail);
            
                }
                if(Input::get('sort')==4){//今日销量升序
                    foreach($statistics_detail as $key=>$sd){
                        $arr[$key]=$sd['sale_num_today'];
                    }
                    array_multisort($arr, SORT_ASC,$statistics_detail);
                }
            }
            $sum_sale_num_today=0;
            $sum_sale_amount_today=0;
            foreach($statistics_detail as $_sd){
                $sum_sale_amount_today+=$_sd['sale_amount_today'];
                $sum_sale_num_today+=$_sd['sale_num_today'];
            }
            
            $statistics['sum_sale_amount_today']=$sum_sale_amount_today;
            $statistics['sum_sale_num_today']=$sum_sale_num_today;
            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("statistics"=>$statistics,"statistics_detail"=>$statistics_detail));
        }while(false);
        Log::info("info", array("system" => "mkt" ,"event" => "save_shops", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
}